﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using EntModApp.EntServices.Properties;

namespace EntModApp.EntServices.Validation
{
  public static class ValidatorHelper
  {
    public static IEnumerable<ValidationResult> GetValidionResults(this object obj, ValidationContext validationContext = null, bool validateAllProperties = true)
    {
      if (obj == null)
        yield return new ValidationResult(Resources.ValidatingObjectCannotBeNull);

      if (validationContext == null) validationContext = new ValidationContext(obj, null, null);
      ICollection<ValidationResult> results = new List<ValidationResult>();

      if (!Validator.TryValidateObject(obj, validationContext, results, validateAllProperties))
        yield return new ValidationResult(Resources.TryValidateObjectFailed);

      foreach (var result in results)
        yield return result;
    }

    public static bool IsValid(this object obj, ValidationContext validationContext = null, bool validateAllProperties = true)
    {
      var results = obj.GetValidionResults(validationContext, validateAllProperties).ToList();
      return results.IsValid();
    }

    public static bool IsValid(this IEnumerable<ValidationResult> results)
    {
      return results.All(r => r == ValidationResult.Success);
    }

    public static void Validate(this object obj, ValidationContext validationContext = null, bool validateAllProperties = true)
    {
      var results = obj.GetValidionResults(validationContext, validateAllProperties).ToList();
      results.Validate();
    }

    public static void Validate(this IEnumerable<ValidationResult> results)
    {
      if (!results.IsValid())
        throw new MultiValidationException(results.Where(r => r != ValidationResult.Success));
    }

  }
}
